package com.steak.orm.builder;

import com.steak.orm.tool.StringUtil;

import java.lang.reflect.Field;

/**
 * @author 刘牌
 * @Title:
 * @date 2022/3/512:54
 */
public class UpdateSQLBuilder extends BaseSQLBuilder {

    public String updateSql(Object obj) throws Exception {
        getTableName(obj);
        sqlBuilder.append(UPDATE).append(tableName).append(SET);
        StringBuilder whereBuilder = new StringBuilder();
        Field[] fields = getFields(obj);
        for (int i = 0; i < fields.length; i++) {
            String fieldName = StringUtil.getLastStr(fields[i].toString());
            Object value = obj.getClass().getMethod(getField(fieldName)).invoke(obj);
            //更新操作主键作为更新条件
            if (hasPrimaryKey(fields[i])) {
                whereBuilder.append(WHERE).append(fieldName).append("=").append(value);
                continue;
            }
            if (null != value && !"".equals(value)) {
                sqlBuilder.append(fieldName).append("=").append("'").append(value).append("'");
                if (i + 1 != fields.length) {
                    sqlBuilder.append(",");
                }
            }
        }
        return sqlBuilder.toString() + whereBuilder;
    }
}
